package com.ggs.rg.ybjb.usermodule.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ggs.rg.ybjb.pojomodule.pojo.Mater;
import com.ggs.rg.ybjb.pojomodule.pojo.TGoodsOrder;
import com.ggs.rg.ybjb.pojomodule.pojo.TOrder;
import com.ggs.rg.ybjb.pojomodule.util.CommonUtil;
import com.ggs.rg.ybjb.pojomodule.util.StringTools;
import com.ggs.rg.ybjb.pojomodule.util.constants.ErrorEnum;
import com.ggs.rg.ybjb.usermodule.exception.OrderException;
import com.ggs.rg.ybjb.usermodule.service.MaterService;
import com.ggs.rg.ybjb.usermodule.service.TGoodsOrderService;
import com.ggs.rg.ybjb.usermodule.service.TOrderService;
import com.ggs.rg.ybjb.usermodule.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author cxw
 * @since 2021-11-02
 */
@RestController
@RequestMapping("/order")
public class TOrderController {

    @Autowired
    TOrderService tOrderService;

    @Autowired
    TGoodsOrderService tGoodsOrderService;

    @Autowired
    MaterService materService;

    @Autowired
    private RedisUtil redisUtil;            //自己写的操作redis的工具类,其实就是封装了redisTemplate的操作

    //获取已付款订单,分页倒序
    @GetMapping("getPaidOrdersByPhone")
    public JSONObject getPaidOrdersByPhone(@RequestParam(required = false) String phone,
                                           @RequestParam(required = false) Integer pagesNumber,
                                           @RequestParam(required = false) Integer status){
        if (StringTools.isNullOrEmpty(phone) || StringTools.isNullOrEmpty(status))
            return CommonUtil.errorJson(ErrorEnum.E_90003);
        if (StringTools.isNullOrEmpty(pagesNumber)){
            pagesNumber = 1;
        }else if (pagesNumber <= 0){
            pagesNumber = 1;
        }
        //返回给前端的订单信息包括,订单基本信息,订单地址,该订单中的所有商品
        //先获取订单基本信息与地址
        JSONObject result = tOrderService.selectOrderByPhone(pagesNumber, phone,status);
        //获取订单中的所有商品
        if (StringTools.isNullOrEmpty(result))
            return CommonUtil.sqlErrorJson("手机号为:"+ phone +"的用户没有未付款订单");
        return CommonUtil.successJson(result);
    }

    //根据oid获取未付款订单详情
    @GetMapping("/getOrderDetailByOid")
    public JSONObject getOrderDetailByOid(@RequestParam String oid){
        JSONObject result = tOrderService.selectTOrderDetailById(oid);
        if (StringTools.isNullOrEmpty(result))
            return CommonUtil.sqlErrorJson("没有查询到指定的未付款订单");
        return CommonUtil.successJson(result);
    }

    //对订单进行付款
    @PostMapping("/payToMoney")
    public JSONObject payToMoney(@RequestParam String oid,@RequestParam Integer aid){
        if (StringTools.isNullOrEmpty(oid) || StringTools.isNullOrEmpty(aid))
            return CommonUtil.errorJson(ErrorEnum.E_90003);
        //调用业务方法进行付款
        JSONObject result = tOrderService.pay(oid, aid);
//        if (StringTools.isNullOrEmpty(result))
//            return CommonUtil.sqlErrorJson("请求失败了了了了....了");
        return result;
    }

    //商品详情页生成订单(生成的订单都是未付款的)
    @PostMapping("/addOrder")
    @Transactional(rollbackFor = OrderException.class)
    public JSONObject addOrder(@RequestBody JSONObject params) throws OrderException {
        //获取请求参数,若是有未填参数则直接返回错误信息
        if (StringTools.isNullOrEmpty(params)){
            return CommonUtil.errorJson(ErrorEnum.E_90003);
        }
        CommonUtil.hasAllRequired(params,"phone,price,goodsInfo");
        //程序执行到这里说明，请求参数必不为空
        String phone = params.getString("phone");
        Double price = params.getDouble("price");
        JSONArray goodsInfo = params.getJSONArray("goodsInfo");
        TOrder tOrder = new TOrder(phone,price);
        boolean addOrderResult = tOrderService.save(tOrder);
        if (addOrderResult){
            //遍历用户购买的所有商品参数
            for (int i = 0 ; i < goodsInfo.size() ; i++){
                JSONObject goodInfo = goodsInfo.getJSONObject(i);
                Integer pid = goodInfo.getInteger("pid");
                Integer count = goodInfo.getInteger("count");
                String oid = tOrder.getOid();
                Mater mater = materService.getById(pid);
                if (mater == null)
                    throw new OrderException("没有查询到商品参数pid为:"+ pid + "数据");
                TGoodsOrder tGoodsOrder = new TGoodsOrder(oid,pid,count);
                boolean addResult = tGoodsOrderService.save(tGoodsOrder);
                if (!addResult)
                    throw new OrderException("插入订单商品关系表失败,订商品号为:"+ pid + ",订单号为:"+oid+"!");
            }
            //向redis缓存中放入一个标志,用来标志订单未付款,30分钟如果还没付款,则这个标志过期,删除数据库该订单记录
            //设置标志10s后过期
            redisUtil.set("orderStatus."+tOrder.getOid(),0,60*30);
        }else{
            return CommonUtil.sqlErrorJson("生成订单失败!!!");
        }
        return CommonUtil.successJson(tOrder.getOid());
    }

    //取消订单,只能取消未付款的订单
    @PostMapping("deleteOrdersByOid")
    public JSONObject deleteOrdersByOid(@RequestParam(required = false) String oid){
        if (StringTools.isNullOrEmpty(oid))
            return CommonUtil.errorJson(ErrorEnum.E_90003);
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0).eq("oid",oid);
        TOrder order = tOrderService.getOne(queryWrapper);
        if (StringTools.isNullOrEmpty(order))
            return CommonUtil.sqlErrorJson("订单不存在或已付款!");
        boolean result = tOrderService.removeById(oid);
        if (result){
            //将缓存中的未付款标志删除
            //手动删除,这样就不会执行"标志失效"的回调函数
            redisUtil.del("orderStatus." + oid);
            return CommonUtil.successJson();
        }
        return CommonUtil.errorJson(ErrorEnum.E_100);
    }



}

